using System;
using NLog;

namespace Datacollection.Services.Logging
{
    /// <summary>
    /// 基于NLog的日志服务实现
    /// </summary>
    public class NLogService : ILoggerService
    {
        private readonly Logger _logger;

        /// <summary>
        /// 日志事件，当有新日志时触发
        /// </summary>
        public event Action<string> LogEvent;

        /// <summary>
        /// 构造函数
        /// </summary>
        public NLogService()
        {
            _logger = LogManager.GetCurrentClassLogger();
        }

        /// <summary>
        /// 调试级别日志
        /// </summary>
        public void Debug(string message)
        {
            var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [DEBUG] {message}";
            _logger.Debug(message);
            OnLogEvent(logMessage);
        }

        /// <summary>
        /// 信息级别日志
        /// </summary>
        public void Info(string message)
        {
            var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [INFO] {message}";
            _logger.Info(message);
            OnLogEvent(logMessage);
        }

        /// <summary>
        /// 警告级别日志
        /// </summary>
        public void Warn(string message)
        {
            var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [WARN] {message}";
            _logger.Warn(message);
            OnLogEvent(logMessage);
        }

        /// <summary>
        /// 错误级别日志
        /// </summary>
        public void Error(string message, Exception ex = null)
        {
            var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [ERROR] {message}";
            if (ex != null)
            {
                logMessage += $". 异常: {ex.Message}";
                _logger.Error(ex, message);
            }
            else
            {
                _logger.Error(message);
            }
            OnLogEvent(logMessage);
        }

        /// <summary>
        /// 致命错误级别日志
        /// </summary>
        public void Fatal(string message, Exception ex = null)
        {
            var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [FATAL] {message}";
            if (ex != null)
            {
                logMessage += $". 异常: {ex.Message}";
                _logger.Fatal(ex, message);
            }
            else
            {
                _logger.Fatal(message);
            }
            OnLogEvent(logMessage);
        }

        /// <summary>
        /// 触发日志事件
        /// </summary>
        protected virtual void OnLogEvent(string message)
        {
            LogEvent?.Invoke(message);
        }
    }
}
    